Param(
  [Parameter(Mandatory=$true)] [string]$GroupId,
  [Parameter(Mandatory=$true)] [string]$ServerName,
  [string]$BasePath = "/ide",
  [string]$ApiHost = "http://localhost:8080",
  [string]$OutFile
)

if (-not $OutFile) {
  $OutFile = "./nginx-shared-$GroupId.conf"
}

if (-not $BasePath.StartsWith('/')) { $BasePath = "/$BasePath" }
if ($BasePath.EndsWith('/')) { $BasePath = $BasePath.Substring(0, $BasePath.Length - 1) }

$url = "$ApiHost/api/users/shared/environment/ide/nginx?groupId=$GroupId&serverName=$ServerName&basePath=$BasePath&operatorRole=admin"
Write-Host "Fetching nginx config from $url"

try {
  $content = Invoke-RestMethod -Uri $url -Method GET
  Set-Content -Path $OutFile -Value $content -Encoding UTF8
  Write-Host "Done. File: $OutFile"
} catch {
  Write-Error "Failed: $($_.Exception.Message)"
  exit 1
}

